package com.qf.czh.controller;

import com.qf.czh.config.VerificationCode;
import com.qf.czh.model.RespBean;
import com.qf.czh.model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class LoginController {
    @Autowired
    RespBean respBean ;
    @RequestMapping("/login")
    public String login(HttpServletRequest request , HttpServletResponse response) throws IOException {
        String action = request.getParameter("action");
        System.out.println("====="+action);
        if ("vcode".equals(action)){
            VerificationCode verificationCode = new VerificationCode();
            BufferedImage image = verificationCode.getImage(); //验证码要按顺序，先生产图片，在生产文字
            String text = verificationCode.getText();
            request.getSession().setAttribute("vcode", text);
            VerificationCode.output(image,response.getOutputStream()); ////用流的方式传回用text制作成图片的码。 用响应的流传回去

        }else {
            return "index";
        }
        return null;
    }

    @RequestMapping("/dologin")
    @ResponseBody
    public RespBean dologin(HttpServletRequest request,User user ,String vcode){
//        System.out.println(vcode);
//        String vc = request.getSession().getAttribute("vcode").toString();
//        if (vcode != null && !vcode.equalsIgnoreCase(vc)){ //万一验证码空，就没有逻辑处理。
//            respBean = RespBean.error("验证码错误");
//
//            return respBean;
//        }

        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
            subject.login(token);
//            subject.logout();
        } catch (AuthenticationException e) {
            e.printStackTrace();
            respBean= RespBean.error("用户名或者密码错误");
            return  respBean;
        }
        respBean =RespBean.ok("登录成功");
        return  respBean;
    }


}
